/*
 * Copyright (c) 2021 Huize (Chengdu) Network Technology Co., LTD All rights reserved.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * huize Service Inc
 * All Rights Reserved @2018
 */
package com.huize.zhike.framework.common.exception;


import com.huize.zhike.framework.common.enumeration.ErrorEnum;

/**
 * 描述: 业务异常类
 *
 * @author tianyuliang
 * @version $Id: BizException.java, v0.1 2019/12/5
 */
public class BizException extends RuntimeException {

    private static final long serialVersionUID = 6935775741288577867L;

    protected ErrorEnum errorEnum;

    protected Throwable throwable;

    /**
     * 业务异常结果类（部分情况下，ErrorEnum枚举不足以表达异常，需要以Object对象做额外补充）
     */
    private BizErrorResult errorResult;


    public BizException(ErrorEnum errorEnum) {
        super(errorEnum.getDesc());
        this.errorEnum = errorEnum;
        this.errorResult = new BizErrorResult(errorEnum.getCode(), errorEnum.getDesc());
    }

    public BizException(ErrorEnum errorEnum, String message) {
        super(errorEnum.getDesc() + ", " + message);
        this.errorEnum = errorEnum;
        this.errorResult = new BizErrorResult(errorEnum.getCode(), message);
    }

    public BizException(String message) {
        super(message);
        this.errorEnum = ErrorEnum.UNKNOWN_ERROR;
        this.errorResult = new BizErrorResult(ErrorEnum.UNKNOWN_ERROR.getCode(), message);
    }

    public BizException(BizErrorResult errorResult) {
        super(errorResult.getErrMsg());
        this.errorEnum = ErrorEnum.of(errorResult.getErrCode());
        this.errorResult = errorResult;
    }

    public BizException(BizErrorResult errorResult, Throwable cause) {
        super(errorResult.getErrMsg(), cause);
        this.errorEnum = ErrorEnum.of(errorResult.getErrCode());
        this.errorResult = errorResult;
    }

    public BizException(String message, Throwable cause) {
        super(message, cause);
        this.throwable = cause;
        this.errorEnum = ErrorEnum.UNKNOWN_ERROR;
        this.errorResult = new BizErrorResult(ErrorEnum.UNKNOWN_ERROR.getCode(), message);
    }

    public BizException(ErrorEnum errorEnum, Throwable cause) {
        super(errorEnum.toString(), cause);
        this.throwable = cause;
        this.errorEnum = errorEnum;
        this.errorResult = new BizErrorResult(errorEnum.getCode(), cause.getMessage());
    }

    public ErrorEnum getErrorEnum() {
        return errorEnum;
    }

    public Throwable getThrowable() {
        return throwable;
    }

    public BizErrorResult getErrorResult() {
        return errorResult;
    }

}
